import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import moment from "moment";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, Dropdown, Popconfirm, message, Divider, Form, Select, Input, DatePicker} from "antd";
import StandardTable from '../../../components/StandardTable';
import RegionalSelection from "../../Form/RegionalSelection";
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;


const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ repair, global,loading }) => ({
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  resdata: repair.resdata,
  loading: repair.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {
    const { pageSize } = this.state;
    const { pagesquery, dispatch} = this.props;
    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });
    // // 养护人
    // dispatch({
    //   type: 'global/fetch_select_maintenman',
    // });
    // 区域列表选择
    dispatch({
      type: 'global/fetch_select_district',
    });
    // 列表
    this.getDataList(pagesquery,pageSize,1);
  }

  // componentWillReceiveProps(nextProps) {
  //   // 外层发起刷新数据请求
  //   if (nextProps.isReloadList === true && this.props.isReloadList === false) {
  //     const { pageSize } = this.state;
  //     this.getDataList({},pageSize,1);
  //     this.props.sotpReloadList();
  //   }
  // }


  getDataList(params,pageSize,currentPage) {
    const { dispatch } = this.props;
    dispatch({
      type: 'repair/fetch_repair_history_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params,
        region:undefined,
      },
    });
  }

  // 安装点位事件
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;

    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){
      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }

  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      repairNum:undefined,
      devType:undefined,
      overTime:undefined,
      maintenanceId:undefined,
      region:{districtId:[],pointId:0},
      createTime:undefined,
    });
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.repairId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if(fieldsValue.region && fieldsValue.region.districtId.length>0){
        fieldsValue.districtId = fieldsValue.region.districtId[fieldsValue.region.districtId.length - 1];
      }
      if(fieldsValue.region && fieldsValue.region.pointId!==0 && fieldsValue.region.districtId.length>0){
        fieldsValue.pointId = fieldsValue.region.pointId;
      }

      if(fieldsValue.createTime){
        fieldsValue.createTime = [fieldsValue.createTime[0].unix() * 1000,fieldsValue.createTime[1].unix() * 1000]
      }

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };

  // 导出
  handleActionExport = (type,id) => {

    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    if(!id && !selectedRows) return;
    const repairIds = id ? [id] : selectedRows;

    dispatch({
      type: 'repair/action_repair_export',
      payload: {
        repairIds
      },
    }).then(()=>{
      this.setState({
        selectedRows: [],
      });
    }).then(()=>{
      message.success("所选维修信息已导出")
    })
  };


  // 链接跳转-------------------
  handleLink = (action,detailInfoId) =>{
    const { dispatch } = this.props;
    const { formValues, currentPage} = this.state;
    let linkpath;
    switch (action) {
      case 'info':
        linkpath = `/fault/history/${detailInfoId}/info`;
        break;
      default:
        break;
    }
    router.push({ pathname:`${linkpath}`,  query: { ...formValues, currentPage} });
  }


  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource, pagesquery } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>

          <Col md={6} sm={24}>
            <FormItem label="维修单号">
              {getFieldDecorator('repairNum',{
                initialValue: pagesquery && pagesquery.repairNum ? pagesquery.repairNum : undefined,
              })(<Input placeholder="请输入养护单号" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="设备类型">
              {getFieldDecorator('devType',{
                initialValue: pagesquery && pagesquery.devType ? pagesquery.devType : undefined,
              })(
                <Select allowClear={true} placeholder="请选择设备类型" style={{ width: '100%' }}>
                  {dictionaries.deviceType && dictionaries.deviceType.map(item => (
                    <Option key={item.value} value={item.value}>{item.label}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="维保单位">
              {getFieldDecorator('maintenanceId',{
                initialValue: pagesquery && pagesquery.maintenanceId ? pagesquery.maintenanceId : undefined,
              })(
                <Select allowClear={true} placeholder="请选择维保单位"   style={{ width: '100%' }}>
                  {selectSource.maintenance && selectSource.maintenance.map(item => (
                    <Option key={item.maintenanceId} value={item.maintenanceId}>{item.maintenanceName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="超时">
              {getFieldDecorator('overTime',{
                initialValue: pagesquery && pagesquery.overTime ? pagesquery.overTime : undefined,
              })(
                <Select allowClear={true} placeholder="请选择" style={{ width: '100%' }}>
                  {dictionaries.yesNo && dictionaries.yesNo.map(item => (
                    <Option key={item.value} value={item.value}>{item.label}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem label="区域点位">
              {getFieldDecorator('region',{
                initialValue: pagesquery && pagesquery.region ? pagesquery.region : {districtId:[],pointId:0},
              })(
                <RegionalSelection
                  districtData={selectSource.districtData}
                  pointData={selectSource.pointData}
                  onChange={this.handleSearchDistrict}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="开始时间">
              {getFieldDecorator('createTime',{
                initialValue: pagesquery && pagesquery.createTime ? [moment(pagesquery.createTime[0]),moment(pagesquery.createTime[1])] : undefined,
              })(
                <RangePicker
                  // showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD"
                  placeholder={['开始时间', '结束时间']}
                />
              )}
            </FormItem>
          </Col>



          <Col md={4} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, dictionaries } = this.props;
    const { selectedRows } = this.state;
    const repairStatus = dictionaries.repairStatus && dictionaries.repairStatus.length>1
      ? dictionaries.repairStatus.map(item=>item.label)
      :[];

    const columns = [
      {
        title: '维修单号',
        dataIndex: 'repairNum',
      },
      // {
      //   title: '设备名称',
      //   dataIndex: 'devName',
      // },
      // {
      //   title: '设备编号',
      //   dataIndex: 'devCode',
      // },
      {
        title: '区域',
        dataIndex: 'districtName',
      },
      {
        title: '点位',
        dataIndex: 'pointName',
      },
      {
        title: '维保单位',
        dataIndex: 'maintenanceName',
      },
      {
        title: '报修人',
        dataIndex: 'creatorName',
      },
      {
        title: '开始时间',
        dataIndex: 'createTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },

      {
        title: '结束时间',
        dataIndex: 'endTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },


      {
        title: '操作',
        // width: 150,
        // fixed:'right',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={'10152'} >
            <a onClick={() => this.handleLink('info',row.repairId)}>详情</a>
            </Authorized>
          </Fragment>
        ),
      },
    ];


    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
{/*          <div className={styles.tableListOperator}>
            <Authorized authority={'10153'} >
            <Button type="default"
                    onClick={() => this.handleActionExport()}
                    disabled={selectedRows.length > 0 ? false : true}
            >
              导出
            </Button>
            </Authorized>

          </div>*/}
          <StandardTable
            selectedRows={selectedRows}
            rowKey="repairId"
            // scroll={{ x: 1500 }}
            loading={loading.reslist}
            data={resdata}
            columns={columns}
            // onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
